package rabbitmq.simple;

import com.rabbitmq.client.*;
import org.pb.basic.util.ConnectionUtils;

import java.io.IOException;

/**
 * 消费者
 * @author pb
 */
public class Comsumer {

    private static final String QUEUE = "simple_producer";

    public static void main(String[] args) throws Exception {

        // 获取到连接
        Connection connection = ConnectionUtils.getConnection();
        // 获取到连接通道
        Channel channel = connection.createChannel();

        // 定义消费者的消费逻辑
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * 声明消费者的消费方式
             * @param consumerTag
             * @param envelope
             * @param properties
             * @param body
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 声明交换机
                String exchange = envelope.getExchange();
                // 获取到路由key
                String routingKey = envelope.getRoutingKey();
                // 获取到消息id
                long deliveryTag = envelope.getDeliveryTag();
                // 解析消息体
                String msg = new String(body, "utf8");
                System.out.println(msg);
            }
        };
        // 消费者监听消息，第一个参数为监听的队列名，第二个为是否开启自动ACK，第三个参数为监听通道的消费者
        channel.basicConsume(QUEUE, false, consumer);
    }

}
